import { GM_registerMenuCommand, GM_getValue, GM_setValue } from "tm";

export function tsToString(ts: number): string {
  return new Date(ts).toLocaleString("zh-CN", {
    timeZone: "UTC",
  });
}

export function defaultTime(): number {
  return Date.now() - new Date().getTimezoneOffset() * 60_000;
}

function getFileName(url: string): string {
  return url.split("#")[0].split("?")[0].split("/").pop() ?? "index.html";
}

export function downCache(blob: Blob, url: string) {
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = getFileName(url);
  Object.assign(a.style, {
    position: "fixed",
    top: "200%",
  });
  document.body.append(a);
  setTimeout(() => {
    a.click();
    a.remove();
  }, 0);
}

export function getLengthOfAny(any: unknown): number {
  return (
    (any as Blob).size ??
    (any as unknown[]).length ??
    JSON.stringify(any as string).length ??
    String(any).length ??
    0
  );
}

export function getTypeOfAny(any: unknown): string {
  return `${typeof any} ${any?.constructor?.name ?? ""}`;
}

export async function gmHostMenu(
  id: string,
  enableTitle: string,
  disableTitle: string,
  action: () => void | Promise<void>,
  prepare?: () => void | Promise<void>,
  reload = true,
  host = location.host,
) {
  const blacks: string[] = JSON.parse(
    (GM_getValue(id) as string) ?? "[]",
  ) as string[];
  if (blacks.includes(host)) {
    await action();
    GM_registerMenuCommand(disableTitle, () => {
      blacks.splice(blacks.indexOf(host), 1);
      GM_setValue(id, JSON.stringify(blacks));
      if (reload) location.reload();
    });
  } else {
    GM_registerMenuCommand(enableTitle, async () => {
      await prepare?.();
      blacks.push(host);
      GM_setValue(id, JSON.stringify(blacks));
      if (reload) location.reload();
    });
  }
}

export function isEmotionUsed(): boolean {
  const styles = document.querySelectorAll("style[data-emotion]");
  return styles.length > 0;
}

export const isDark: boolean = matchMedia(
  "(prefers-color-scheme: dark)",
).matches;
